package com.cc8w.config;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import com.cc8w.shiro.ShiroRealm;

/**
 * 依据：https://gitee.com/fps2tao/java_xinqi/blob/master/src/main/resources/applicationContext.xml
 * springboot Shiro的配置文件
 * @author Administrator
 *
 */


@Configuration
@PropertySource("classpath:shiro.properties")
public class ShiroConfig {
	
	@Value("${shiro.hashAlgorithmName}")
	private String hashAlgorithmName;
	@Value("${shiro.hashIterations}")
	private int hashIterations;
	
	
	
	/**
	 * (1).声明凭证匹配器(密码加密用)
	 * @return
	 */
	@Bean
	public CredentialsMatcher credentialsMatcher() {
		HashedCredentialsMatcher cm = new HashedCredentialsMatcher();
		cm.setHashAlgorithmName(this.hashAlgorithmName);
		cm.setHashIterations(this.hashIterations);
		return cm;
		
	}
	/**
	 * (2).配置Realm(自己定义的类)
	 */
	@Bean
	public ShiroRealm shiroReaml() {
		
		ShiroRealm sr = new ShiroRealm();
		sr.setCredentialsMatcher(this.credentialsMatcher());
		return sr;
	}
	
	/**
	 * (3). 创建安全管理器
	 * @return
	 */
	
	@Bean
	public DefaultWebSecurityManager securityManager() {
		DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();
		dwsm.setRealm(this.shiroReaml());
		return dwsm;
		
	}
	
	/**
	 * (4). 配置过滤器链
	 * @return
	 */
	@Bean
	public ShiroFilterFactoryBean shiroFilter() {
		ShiroFilterFactoryBean sffb = new ShiroFilterFactoryBean();
		sffb.setSecurityManager(this.securityManager());//Shiro的核心安全接口
		sffb.setSuccessUrl("/admin/index/welcome");
		sffb.setLoginUrl("/admin/login/login");//要求登录时的链接
		//用户访问未对其授权的资源时，所显示的连接
		sffb.setUnauthorizedUrl("/sys/admin/unauthorized");
		
		//过滤器链的定义,从上往下顺序执行,一般将/**放在最后
		Map<String, String> map = new HashMap<>();    
        map.put("/logout", "logout");//登出
        map.put("/static/**", "anon");
        map.put("/templates/**", "anon");
        map.put("/**", "authc");//对所有用户认证	
		sffb.setFilterChainDefinitionMap(map);
		return sffb;
		
	}
	
	
	
	
	

	

}
